//
//  ExamQuestionWriteCollectionViewCell.m
//  JPWords
//
//  Created by 梁淑婷 on 2024/7/22.
//

#import "ExamQuestionWriteCollectionViewCell.h"
#import <WebKit/WebKit.h>

@interface ExamQuestionWriteCollectionViewCell()<WKUIDelegate,WKNavigationDelegate>

@property(nonatomic,strong)UIView *topView;
@property(nonatomic,strong)UIScrollView *bgScrollView;
@property(nonatomic,strong)WKWebView *titleWebView;
@property(nonatomic,strong)UIView *exampleBgView;
@property(nonatomic,strong)UILabel *exampleTitleLabel;
@property(nonatomic,strong)WKWebView *exampleWebView;
@property(nonatomic,assign)CGFloat total_h;
@property(nonatomic,strong)UIView *questionView;
@property(nonatomic,strong)WKWebView *questionWebView;


@end

@implementation ExamQuestionWriteCollectionViewCell

-(instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if(self){
        self.currentAvailableWidth = frame.size.width;
        [self createUI];
    }
    return self;
}

-(void)createUI{
    
    self.backgroundColor = [UIColor whiteColor];
    
    self.topView = [[UIView alloc]init];
    self.topView.backgroundColor = UIColorHex_(0xFF781D,0.1);
    [self.contentView addSubview:self.topView];
    [self.topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.mas_equalTo(@0);
        make.height.mas_equalTo(@40);
    }];
    UILabel *tipLabel = [[UILabel alloc]init];
    tipLabel.backgroundColor = [UIColor clearColor];
    tipLabel.font = JPUIFontPingFangSCRegular(14);
    tipLabel.textColor = UIColorHex_(0xFF781D,0.8);
    tipLabel.text = @"*本题不支持作答，可在交卷后查看范文";
    [self.topView addSubview:tipLabel];
    [tipLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(@10);
        make.left.mas_equalTo(@16);
        make.height.mas_equalTo(@20);
        make.right.mas_equalTo(@-16);
    }];
    self.topView.hidden = YES;
    
    self.bgScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0,40,self.currentAvailableWidth,self.height-40)];
    self.bgScrollView.backgroundColor =  [UIColor whiteColor];
    self.bgScrollView.showsVerticalScrollIndicator = NO;
    [self.contentView addSubview:self.bgScrollView];
    
    //大题题目 写作题目
    self.questionView = [[UIView alloc]initWithFrame:CGRectMake(16,14,self.currentAvailableWidth-32,0)];
    self.questionView.layer.cornerRadius = 10;
    self.questionView.layer.masksToBounds = YES;
    self.questionView.backgroundColor = UIColorHex_(0xFF781D,0.1);
    [self.bgScrollView addSubview:self.questionView];
    [self createQuestionWebView];
    
    //范文
    self.exampleBgView = [[UIView alloc]initWithFrame:CGRectMake(16,CGRectGetMaxY(self.titleWebView.frame)+21,self.currentAvailableWidth-32, 53+16)];
    self.exampleBgView.backgroundColor = KbgColor;
    self.exampleBgView.layer.cornerRadius = 10;
    self.exampleBgView.layer.masksToBounds = YES;
    [self.bgScrollView addSubview:self.exampleBgView];
    
    __weak typeof(self)self_weak_  = self;
    self.exampleTitleLabel = [[UILabel alloc]init];
    self.exampleTitleLabel.font = JPUIFontPingFangSCMedium(15);
    self.exampleTitleLabel.textColor = KFontBlackColor;
    self.exampleTitleLabel.text = @"范文：";
    [self.exampleBgView addSubview:self.exampleTitleLabel];
    [self.exampleTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(@16);
        make.top.mas_equalTo(@16);
        make.height.mas_equalTo(@21);
        make.width.mas_equalTo(self_weak_.currentAvailableWidth-64);
    }];
    
    //例子
    [self createExampleWebView];
    
    self.exampleTitleLabel.hidden = YES;
    self.exampleBgView.hidden = YES;
    self.exampleWebView.hidden = YES;
    
}

#pragma mark - 创建题目webview
-(void)createQuestionWebView{
    //大题题目
    NSString *jScript0 = [NSString stringWithFormat:@"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=%f'); document.getElementsByTagName('head')[0].appendChild(meta);", self.currentAvailableWidth - 64];
    WKUserScript *wkUScript0 = [[WKUserScript alloc] initWithSource:jScript0 injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    WKUserContentController *wkUController0 = [[WKUserContentController alloc] init];
    [wkUController0 addUserScript:wkUScript0];
    WKWebViewConfiguration *wkWebConfig0 = [[WKWebViewConfiguration alloc] init];
    wkWebConfig0.userContentController = wkUController0;
    self.questionWebView = [[WKWebView alloc] initWithFrame:CGRectMake(16, 10, self.currentAvailableWidth - 64,0) configuration:wkWebConfig0];
    self.questionWebView.scrollView.showsVerticalScrollIndicator = NO;
    self.questionWebView.scrollView.showsHorizontalScrollIndicator = NO;
    self.questionWebView.UIDelegate = self;
    self.questionWebView.navigationDelegate = self;
    self.questionWebView.scrollView.bounces = NO;
    self.questionWebView.backgroundColor = [UIColor clearColor];
    self.questionWebView.scrollView.backgroundColor = [UIColor clearColor];
    self.questionWebView.scrollView.scrollEnabled = NO;
    self.questionWebView.opaque = NO;
    [self.questionView addSubview:self.questionWebView];
    self.questionView.hidden = YES;
    
    //写作题目
    NSString *jScript = [NSString stringWithFormat:@"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=%f'); document.getElementsByTagName('head')[0].appendChild(meta);", self.currentAvailableWidth - 40];
    WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    WKUserContentController *wkUController = [[WKUserContentController alloc] init];
    [wkUController addUserScript:wkUScript];
    WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
    wkWebConfig.userContentController = wkUController;
    self.titleWebView = [[WKWebView alloc]initWithFrame:CGRectMake(20,24,self.currentAvailableWidth-40,0) configuration:wkWebConfig];
    self.titleWebView.scrollView.showsVerticalScrollIndicator = NO;
    self.titleWebView.scrollView.showsHorizontalScrollIndicator = NO;
    self.titleWebView.UIDelegate = self;
    self.titleWebView.navigationDelegate = self;
    self.titleWebView.scrollView.bounces = NO;
    self.titleWebView.backgroundColor = [UIColor clearColor];
    self.titleWebView.scrollView.backgroundColor = [UIColor clearColor];
    self.titleWebView.scrollView.scrollEnabled = NO;
    self.titleWebView.opaque = NO;
    [self.bgScrollView addSubview:self.titleWebView];
}

#pragma mark - 创建例子webview
-(void)createExampleWebView{
    
    NSString *jScript2 = [NSString stringWithFormat:@"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=%f'); document.getElementsByTagName('head')[0].appendChild(meta);", self.currentAvailableWidth - 64];
    WKUserScript *wkUScript2 = [[WKUserScript alloc] initWithSource:jScript2 injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    WKUserContentController *wkUController2 = [[WKUserContentController alloc] init];
    [wkUController2 addUserScript:wkUScript2];
    WKWebViewConfiguration *wkWebConfig2 = [[WKWebViewConfiguration alloc] init];
    wkWebConfig2.userContentController = wkUController2;
    self.exampleWebView = [[WKWebView alloc]initWithFrame:CGRectMake(16,53,self.currentAvailableWidth-64,0) configuration:wkWebConfig2];
    self.exampleWebView.scrollView.showsVerticalScrollIndicator = NO;
    self.exampleWebView.scrollView.showsHorizontalScrollIndicator = NO;
    self.exampleWebView.UIDelegate = self;
    self.exampleWebView.navigationDelegate = self;
    self.exampleWebView.scrollView.bounces = NO;
    self.exampleWebView.backgroundColor = [UIColor clearColor];
    self.exampleWebView.scrollView.backgroundColor = [UIColor clearColor];
    self.exampleWebView.scrollView.scrollEnabled = NO;
    self.exampleWebView.opaque = NO;
    [self.exampleBgView addSubview:self.exampleWebView];
    self.exampleWebView.hidden = YES;
}


-(void)setModel:(ExamQuestionModel *)model{
    _model = model;
    
    self.titleWebView.frame =  CGRectMake(20,24,self.currentAvailableWidth-40,0);
    self.questionWebView.frame = CGRectMake(16, 10, self.currentAvailableWidth - 64,0);
    self.exampleWebView.frame = CGRectMake(16,53,self.currentAvailableWidth-64,0);
    
    CGFloat total_h = 24+93;

    if(model.name &&![model.name isEqualToString:@""]){
        self.questionView.hidden = NO;
        NSString *paddingStyle = @"<style>body{background-color: transparent; margin: 0; padding: 0; font-family: 'PingFang-SC-Regular'; font-size: 14px; color: #FF781D;} img{max-width:100%; height:auto;} *{word-wrap: break-word;}</style>";
        NSString *fullHTML = [NSString stringWithFormat:@"<html><head>%@</head><body>%@</body></html>", paddingStyle,model.name];
        if(![model.name containsString:@"<p>"]){
            fullHTML = [NSString stringWithFormat:@"<html><head>%@</head><body><p>%@</p></body></html>", paddingStyle,model.name];
        }
        [self.questionWebView loadHTMLString:fullHTML baseURL:nil];
        total_h = total_h-24+14+self.questionView.height+24;
    }else{
        self.questionView.hidden = YES;
    }
    
    NSString *htmlContent = model.content?model.content:@"<p></p>";
    // 题目序号
    NSString *titleNumber = @"";
    if(model.sortId&&![model.sortId isEqualToString:@""]){
        titleNumber = [NSString stringWithFormat:@"%@.",model.sortId];
    }
    // 查找第一个 <p> 标签的位置
    NSRange pTagRange = [htmlContent rangeOfString:@"<p>"];
    // 根据是否找到 <p> 标签进行处理
    NSString *combinedHTMLContent;
    if (pTagRange.location != NSNotFound) {
        // 找到 <p> 标签，插入序号
        combinedHTMLContent = [htmlContent stringByReplacingCharactersInRange:NSMakeRange(pTagRange.location + pTagRange.length, 0) withString:titleNumber];
    } else {
        // 未找到 <p> 标签，直接在字符串前面拼接序号
        combinedHTMLContent = [NSString stringWithFormat:@"<p>%@%@</p>",titleNumber, htmlContent];
    }

    // 设置样式
    NSString *paddingStyle = @"<style>body{background-color: transparent; margin: 0; padding: 0; font-family: 'PingFang-SC-Regular'; font-size: 16px; color: #1C1F1E;} img{max-width:100%; height:auto;letter-spacing: 1px;} *{word-wrap: break-word;}</style>";
    NSString *fullHTML = [NSString stringWithFormat:@"<html><head>%@</head><body>%@</body></html>", paddingStyle, combinedHTMLContent];
    [self.titleWebView loadHTMLString:fullHTML baseURL:nil];
    
    if(self.testType == 2||self.testType == 3||self.testType == 4){
        
        self.topView.hidden = YES;
        self.exampleBgView.hidden = NO;
        self.exampleWebView.hidden = NO;
        self.exampleTitleLabel.hidden = NO;
        self.bgScrollView.frame = CGRectMake(0,0,self.currentAvailableWidth,self.height);
        NSString *paddingStyle2 = @"<style>body{background-color: transparent; margin: 0; padding: 0; font-family: 'PingFang-SC-Regular'; font-size: 16px; color: #1C1F1E;} img{max-width:100%; height:auto;letter-spacing: 1px;} *{word-wrap: break-word;}</style>";
        NSString *fullHTML2 = [NSString stringWithFormat:@"<html><head>%@</head><body>%@</body></html>", paddingStyle2, model.analysis];
        if(![model.analysis containsString:@"<p>"]){
            fullHTML2 = [NSString stringWithFormat:@"<html><head>%@</head><body><p>%@</p></body></html>", paddingStyle2, model.analysis];
        }
        [self.exampleWebView loadHTMLString:fullHTML2 baseURL:nil];
        
        total_h = total_h+21+53+16;
       
    }else{
        self.topView.hidden = NO;
        self.exampleBgView.hidden = YES;
        self.exampleWebView.hidden = YES;
        self.exampleTitleLabel.hidden = YES;
        self.bgScrollView.frame = CGRectMake(0,40,self.currentAvailableWidth,self.height-40);
    }
    
    self.total_h = total_h;
    self.bgScrollView.contentSize = CGSizeMake(self.currentAvailableWidth,total_h);
    
}

#pragma mark - webview delegate
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    // 执行 JavaScript 以获取页面内容的高度
    [webView evaluateJavaScript:@"document.documentElement.scrollHeight" completionHandler:^(id result, NSError *error) {
        if (!error) {
            CGFloat height = [result doubleValue];
            CGFloat h = height-16;
            if(h < 0){
                h = 0;
            }
            if ([webView isEqual:self.titleWebView]) {
                if(self.questionView.height > 0){
                    webView.frame = CGRectMake(16,CGRectGetMaxY(self.questionView.frame)+24,self.currentAvailableWidth - 40,h);
                }else{
                    webView.frame = CGRectMake(16,24,self.currentAvailableWidth - 40,h);
                }
                self.total_h = self.total_h+h;
                self.exampleBgView.top = CGRectGetMaxY(self.titleWebView.frame)+21;
            }else if ([webView isEqual:self.exampleWebView]){
                webView.frame = CGRectMake(16,53,self.currentAvailableWidth-64,h);
                self.exampleBgView.frame = CGRectMake(16,CGRectGetMaxY(self.titleWebView.frame)+21,self.currentAvailableWidth-32,53+16+h);
                self.total_h = self.total_h+h;
            }else if ([webView isEqual:self.questionWebView]){
                webView.frame = CGRectMake(16,10,self.currentAvailableWidth - 64,h);
                if(h == 0){
                    self.questionView.frame = CGRectMake(16,14,self.currentAvailableWidth-32,0);
                    self.questionView.hidden = YES;
                    self.titleWebView.top = 24;
                }else{
                    self.questionView.hidden = NO;
                    self.questionView.frame = CGRectMake(16,14,self.currentAvailableWidth-32,h+20);
                    self.total_h = self.total_h+h+20;
                    self.titleWebView.top = CGRectGetMaxY(self.questionView.frame)+24;
                }
                self.exampleBgView.top = CGRectGetMaxY(self.titleWebView.frame)+21;
    
            }
            self.bgScrollView.contentSize = CGSizeMake(self.currentAvailableWidth,self.total_h);
        } else {
            NSLog(@"获取 WebView 内容高度失败: %@", error.localizedDescription);
        }
    }];
}


@end
